package com.katesoft.scale4j.rttp.jobs.tasklets;

import org.perf4j.aop.Profiled;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.katesoft.scale4j.common.services.IBeanNameReferences;
import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.log.Logger;
import com.katesoft.scale4j.persistent.client.LocalHibernateTemplate;
import com.katesoft.scale4j.rttp.client.ISpringContextAccessor;

/**
 * @author kate2007
 */
public abstract class AutowireCapableTasklet implements Tasklet {
   protected Logger logger = LogFactory.getLogger(getClass());

   @Autowired
   @Qualifier(value = IBeanNameReferences.HIBERNATE_TEMPLATE)
   protected LocalHibernateTemplate hibernateTemplate;

   @Override
   @Profiled
   public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
      try {
         ISpringContextAccessor.ACCESSOR.autowire(this);
      } catch (RuntimeException e) {
         logger.error("unable to autowire bean, make sure you are running inside spring context", e);
         throw e;
      }
      return doExecute(contribution, chunkContext);
   }

   protected abstract RepeatStatus doExecute(StepContribution contribution,
            ChunkContext chunkContext);
}
